package com.lzp.systemopt.nfc

import android.app.PendingIntent
import android.content.Intent
import android.nfc.NfcAdapter
import android.os.Bundle
import com.base.BaseActivity
import com.lzp.systemopt.R
import com.utils.toast.ToastUtils

/**
 * @describe:
 * @Author: lixiaopeng
 * @Date: 2021/7/14
 */
class AppNfcActivity : BaseActivity(){

    private val mNfcAdapter: NfcAdapter? by lazy { NfcAdapter.getDefaultAdapter(this) }
    private val mPendingIntent: PendingIntent by lazy { PendingIntent.getActivity(
            this,
            0,
            Intent(applicationContext, javaClass).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
            0) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.write_nfc_actvity)

        initView()
    }

    override fun initView() {
        super.initView()
        if (mNfcAdapter == null) {
            ToastUtils.toastText("不支持NFC")
        } else if (!mNfcAdapter!!.isEnabled) {
            ToastUtils.toastText("请在系统设置中开启NFC功能")
        }
    }

    override fun onResume() {
        super.onResume()
        // 优先于其它
        mNfcAdapter?.enableForegroundDispatch(this, mPendingIntent, null, null)
        processIntent(intent)
    }

    override fun onPause() {
        super.onPause()
        mNfcAdapter?.disableForegroundDispatch(this)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        if (intent == null) return
        setIntent(intent)
        processIntent(intent)
    }

    private var mProcessedIntent: Intent? = null
    private fun processIntent(intent: Intent) {
        if (mProcessedIntent?.hashCode() == intent.hashCode()) {
            return
        }
        val action = intent.action
        if (NfcAdapter.ACTION_NDEF_DISCOVERED == action) {
            mProcessedIntent = intent
        } else if (NfcAdapter.ACTION_TAG_DISCOVERED == action || NfcAdapter.ACTION_TECH_DISCOVERED == action) {
            mProcessedIntent = intent
        } else {
            return
        }
        NfcHelper.writeNdefPkg(intent,"com.lzp.appexp","https://www.bai.com/share")
    }

}